<?php

namespace App\Http\Controllers\Freelancer;

use App\Http\Controllers\Controller;
use App\Models\TaskApplication;
use App\Models\ContractSignHistory;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class ContractController extends Controller
{
    /**
     * 获取用户的合同/申请记录列表
     */
    public function index(Request $request)
    {
        try {
            $user = $request->user();

            // 获取用户的所有申请记录
            $applications = TaskApplication::where('freelancer_id', $user->id)
                ->orderBy('created_at', 'desc')
                ->get();

            // 转换真实数据格式
            $data = $applications->map(function ($app) {
                return [
                    'id' => $app->id,
                    'taskId' => $app->task_id,
                    'taskName' => $app->task->name ?? '未知任务',
                    'serviceType' => $app->task->service_type ?? '未知类型',
                    'status' => $app->status,
                    'minFee' => $app->task->min_fee ?? 0,
                    'maxFee' => $app->task->max_fee ?? 0,
                    'workLocation' => $app->task->work_location ?? '未知',
                    'startTime' => $app->task->start_time ?? '',
                    'endTime' => $app->task->end_time ?? '',
                    'createdAt' => $app->created_at->format('Y-m-d H:i:s'),
                    'reviewNote' => $app->review_note ?? ''
                ];
            });

            return response()->json([
                'code' => 0,
                'message' => '获取成功',
                'data' => $data
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'code' => 1,
                'message' => '获取记录失败',
                'data' => null
            ]);
        }
    }

    /**
     * 获取单个合同/申请记录详情
     */
    public function show(Request $request, $id)
    {
        try {
            $user = $request->user();

            $application = TaskApplication::where('freelancer_id', $user->id)
                ->where('id', $id)
                ->first();

            if (!$application) {
                return response()->json([
                    'code' => 1,
                    'message' => '记录不存在',
                    'data' => null
                ]);
            }

            $data = [
                'id' => $application->id,
                'taskId' => $application->task_id,
                'taskName' => $application->task->name ?? '未知任务',
                'serviceType' => $application->task->service_type ?? '未知类型',
                'status' => $application->status,
                'minFee' => $application->task->min_fee ?? 0,
                'maxFee' => $application->task->max_fee ?? 0,
                'workLocation' => $application->task->work_location ?? '未知',
                'startTime' => $application->task->start_time ?? '',
                'endTime' => $application->task->end_time ?? '',
                'createdAt' => $application->created_at->format('Y-m-d H:i:s'),
                'reviewNote' => $application->review_note ?? '',
                'applicantInfo' => [
                    'name' => $application->name,
                    'phone' => $application->phone,
                    'idCard' => $application->id_card,
                    'address' => optional($application->freelancer)->address ?? '',
                    'experience' => $application->experience,
                ]
            ];

            return response()->json([
                'code' => 0,
                'message' => '获取成功',
                'data' => $data
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'code' => 1,
                'message' => '获取记录详情失败',
                'data' => null
            ]);
        }
    }

    /**
     * 下载合同文件
     */
    public function download(Request $request, int $id)
    {
        $user = $request->user();

        $application = TaskApplication::where('freelancer_id', $user->id)
            ->where('id', $id)
            ->first();

        if (! $application) {
            return response()->json([
                'code' => 404,
                'message' => '合同不存在或无权访问',
                'data' => null,
            ], 404);
        }

        if ($application->status !== 'approved') {
            return response()->json([
                'code' => 422,
                'message' => '当前状态不支持下载合同',
                'data' => null,
            ], 422);
        }

        $history = ContractSignHistory::query()
            ->where('task_id', $application->task_id)
            ->where('freelancer_id', $user->id)
            ->latest('created_at')
            ->first();

        if (! $history) {
            Log::warning('[Contract] download attempted but sign history missing', [
                'application_id' => $application->id,
                'freelancer_id' => $user->id,
            ]);

            return response()->json([
                'code' => 404,
                'message' => '尚未生成合同文件，请稍后重试',
                'data' => null,
            ], 404);
        }

        if (! empty($history->contract_file_path)) {
            $disk = config('filesystems.default');
            $filePath = $history->contract_file_path;
            $fileName = $history->contract_file_name ?? "contract-{$application->id}.pdf";

            if (Storage::disk($disk)->exists($filePath)) {
                return Storage::disk($disk)->download($filePath, $fileName);
            }

            Log::warning('[Contract] contract file path recorded but not found', [
                'application_id' => $application->id,
                'freelancer_id' => $user->id,
                'path' => $filePath,
            ]);
        }

        if (! empty($history->contract_download_url)) {
            return response()->json([
                'code' => 0,
                'message' => '即将跳转至合同下载链接',
                'data' => [
                    'download_url' => $history->contract_download_url,
                ],
            ]);
        }

        Log::error('[Contract] contract download failed, no file recorded', [
            'application_id' => $application->id,
            'freelancer_id' => $user->id,
        ]);

        return response()->json([
            'code' => 404,
            'message' => '合同文件尚未生成，请稍后重试',
            'data' => null,
        ], 404);
    }
}
